<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/1/4
 * Time: 15:12
 */

namespace app\api\controller;


use think\Db;

class Timeing
{
    /**
     * 定时消息推送
     */
    public function sendNotice(){
        //未发送的消息列表
        $lists = Db::table('up_notice')
            ->field('n_id, n_time, n_publish_time')
            ->where('n_status', 0)
            ->select();
        $time = date('Y-m-d H:i:s');
        //修改状态
        $list = [];
        foreach($lists as $key => $va){
            if($time >= $va['n_publish_time']){//当前时间大于等于设定的时间
                $res = Db::table('up_notice')->where('n_id', $va['n_id'])->setField('n_status', 1);
                if($res){
                    $m_ids = Db::table('up_factory_member')
                        ->column('m_id');
                    foreach($m_ids as $k => $val){
                        $v = (string)$val;
                        array_push($list, $v);
                    }
                    try{
                        $this->Jpush1(2, $list, '消息发布', 1);
                    }catch(\Exception $e){
        
                    }
                }
            }
        }
    }
    
    /**
     * 定时启动Banner
     */
    public function sendStartBanner(){
        //未发送启动页列表
        $lists = Db::table('up_banner_start')
            ->field('b_id, b_publish_time')
            ->where('b_status', 0)
            ->select();
        //修改状态
        $time = date('Y-m-d H:i:s');
        foreach($lists as $key => $va){
            if($time >= $va['b_publish_time']){
                Db::table('up_banner_start')->where('b_id', $va['b_id'])->setField('b_status', 1);
            }
        }
    }
    
    /**
     * 极光推送--推送消息类型
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $code
     * @return array
     */
    public function Jpush1($type,$alias,$message,$code)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => [
                'key' => $code
            ]
        ]);
        return $push->send();
    }
}